/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { isFunction } from 'lodash';
import React, { useContext, useEffect, useState } from 'react';
import Animate from './animate-child';
import { ObserverContext } from './_utils/context';
import type { AnimateOpts, AnimateStatusChangeParams, ObserverProps } from './_utils/types';

const AnimateConsumer: React.FC<ObserverProps> = (props) => {
  const { children, show, next, onEnd, onStart, ...rest } = props;
  const value = useContext(ObserverContext);

  const [animate, setAnimate] = useState<AnimateOpts | null>();

  const { show: valueShow = show } = value;
  useEffect(() => {
    // 出场后，清空next
    if (next && !valueShow) {
      setAnimate(null);
    }
  }, [valueShow]);

  // 首次动画开始
  const handleStart = (params: AnimateStatusChangeParams) => {
    if (next && params.rounds === 'first') {
      setAnimate(null);
    }
    if (isFunction(onStart)) {
      onStart(params);
    }
  };

  // 首次动画结束
  const handleEnd = (params: AnimateStatusChangeParams) => {
    if (next && params.rounds === 'first') {
      setAnimate(next);
    }
    if (isFunction(onEnd)) {
      onEnd(params);
    }
  };

  return (
    <Animate show={show} {...value} {...rest} {...animate} onStart={handleStart} onEnd={handleEnd}>
      {children}
    </Animate>
  );
};

AnimateConsumer.defaultProps = {
  show: true,
};

export default AnimateConsumer;
